package com.hbsoft.lms.service;

import com.hb.bean.CallResult;
import com.hb.util.StringUtil;
import com.hbsoft.lms.bean.AreaUserBean;
import com.hbsoft.lms.bean.BankBean;
import com.hbsoft.lms.dao.HBUserDao;
import com.hbsoft.lms.dao.service.AreaUserBeanDaoService;
import com.hbsoft.lms.dao.service.BankBeanDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BankAreaService {

    @Autowired
    BankBeanDaoService bankBeanDaoService;

    @Autowired
    AreaUserBeanDaoService areaUserBeanDaoService;
    @Autowired
    HBUserDao hbUserDao;

    @Transactional
    public CallResult<String> removeById(Integer id_prikey) throws Exception {
        CallResult<String> result = new CallResult<>();
        BankBean bank = bankBeanDaoService.getById(id_prikey);
        if (null != bank) {
            bankBeanDaoService.removeOne(id_prikey);

            AreaUserBean areaUserBean = new AreaUserBean();
            areaUserBean.setCode(bank.getCode());
            List<AreaUserBean> all = areaUserBeanDaoService.getAll(areaUserBean);
            if (all != null && all.size() != 0) {
                Integer roleId = hbUserDao.findRoleByAttr("BANKBRANCH");
                Map<String, Object> mapParam = new HashMap<>();
                for (AreaUserBean aub : all) {
                    Integer user_id_prikey = hbUserDao.findUserNameCount(aub.getTel());
                    mapParam.put("roleId", roleId);
                    mapParam.put("userId", user_id_prikey);
                    Map<String, Object> roleUserMap = hbUserDao.selectRoleByUser(mapParam);
                    if (roleUserMap != null) {
                        String roleUserId = (String) roleUserMap.get("id_prikey");
                        if (!StringUtil.isEmpty(roleUserId)) {
                            hbUserDao.delRoleByUserById(Integer.valueOf(roleUserId));
                        }
                    }
                }
                areaUserBeanDaoService.remove(areaUserBean);
            }
            result.setCode(0);
            result.setMessage("操作成功");
        } else {
            result.setCode(400);
            result.setMessage("操作失败");
        }
        return result;
    }
}
